package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyComment;
import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.query.TravelCommentQuery;
import cn.wolfcode.wolf2w.repository.TravelCommentRepository;
import cn.wolfcode.wolf2w.service.ITravelCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private MongoTemplate template;
    @Autowired
    private TravelCommentRepository repository;

    @Override
    public void save(TravelComment travelComment) {
        travelComment.setId(null);
        repository.save(travelComment);
    }

    @Override
    public void update(TravelComment travelComment) {
        repository.save(travelComment);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public TravelComment get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<TravelComment> getComments(TravelCommentQuery qo) {
        Query query = new Query() ;
        query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        long count = template.count(query, StrategyComment.class);
        if (count == 0) {
            Page.empty();
        }
        if (count % qo.getPageSize() == 0 && qo.getCurrentPage() > 1) {
            qo.setCurrentPage(qo.getCurrentPage() - 1);
        }
        List<TravelComment> comments = template.find(query, TravelComment.class);

        return comments;
    }

    @Override
    public void commentAdd(TravelComment comment) {
        comment.setCreateTime(new Date());
        if(comment.getRefComment().id!=null){
            TravelComment travelComment = this.get(comment.getRefComment().id);
            comment.setRefComment(travelComment);
            }
        this.save(comment);

    }

    @Override
    public List<TravelComment> list() {
        return repository.findAll();
    }




}

